import json

import logging

import re
from flask import Blueprint, jsonify
from flask import abort
from flask import current_app,g
from flask import current_app
from flask import g
from flask import request
from flask import session

from ihome_tenancy import redis_store, db

from ihome_tenancy.models import Area, Facility, House, User, Order
from ihome_tenancy.models import Area, Facility, House, HouseImage

from ihome_tenancy.models import Area, Facility, House, User

from ihome_tenancy.utils.my_decorators import is_login
from ihome_tenancy.utils.qiniu_sdk import put_qiniu
from ihome_tenancy.utils.response_code import RET, ret_map

house_blueprint = Blueprint('house',__name__)


@house_blueprint.route('/house/index',methods=['GET'])
def house_index():
    #f房屋首页的显示
    code=RET.DATAERR
    user_name = ''
    if 'user_id' in session:
        #p判断用户是否登录
        user = User.query.filter_by(id=session['user_id']).first()
        user_name = user.name
        code = RET.OK
    #数据存入到redis
    hlist = redis_store.get('hlist1')
    if not hlist:
        #查询房屋最新的5条数据
        hlist2 = House.query.order_by(House.create_time.desc())[0:5]
        hlist = [house_info.to_dict() for house_info in hlist2]
    else:
        hlist=json.loads(hlist.decode())
    alist = area_get()

    return jsonify(code=code,name=user_name,hlist=hlist,alist=alist)

@house_blueprint.route('/house/', methods=['POST'])
@is_login
def newhouse_save():
    """发布新房源"""
    # 1 获取参数
    user = g.user
    data_dict = request.form.to_dict()
    title = data_dict.get('title')
    price = data_dict.get('price')
    area_id = data_dict.get('area_id')
    address = data_dict.get('address')
    room_count = data_dict.get('room_count')
    acreage = data_dict.get('acreage')
    unit = data_dict.get('unit')
    capacity = data_dict.get('capacity')
    beds = data_dict.get('beds')
    deposit = data_dict.get('deposit')
    min_days = data_dict.get('min_days')
    max_days = data_dict.get('max_days')
    # 获取配套设施，返回一个列表
    facility_ids = request.form.getlist('facility')

    # 2 检验参数
    if not all([title, price, area_id, address, room_count, acreage, unit, capacity, beds, deposit, min_days, max_days]):
        return jsonify(code=RET.PARAMERR, msg=ret_map[RET.PARAMERR])

    try:
        price = int(price)
        deposit = int(deposit)
    except Exception as e:
        logging.error('数据类型错误')
        return jsonify(code=RET.PARAMERR, msg=ret_map[RET.PARAMERR])

    # 3 创建数据
    house = House()
    house.user_id = user.id
    house.area_id = area_id
    house.title = title
    house.price = price
    house.address = address
    house.room_count = room_count
    house.acreage = acreage
    house.unit = unit
    house.capacity = capacity
    house.beds = beds
    house.deposit = deposit
    house.min_days = min_days
    house.max_days = max_days

    if facility_ids:
        facilities = Facility.query.filter(Facility.id.in_(facility_ids)).all()
        house.facilities = facilities

    # 4 保存数据到数据库
    try:
        house.add_update()
    except Exception as e:
        logging.error(e)
        db.session.rollback()
        return jsonify(code=RET.DBERR, msg=ret_map[RET.DBERR])

    # 5 更新redis中最新的五条房屋数据
    hlist = House.query.order_by(House.id.desc())[:5]
    hlist2 = [house.to_dict() for house in hlist]
    redis_store.setex('hlist', 24*3600, json.dumps(hlist2))

    # 6 返回数据
    return jsonify(code=RET.OK, house_id=house.id)

@house_blueprint.route('/house/<int:id>', methods=['GET'])
def house_detail(id):
    house = House.query.get(id)
    # 查询设施信息
    facility_list = facility_get()
    # 判断当前房屋信息是否为当前登录的用户发布，如果是则不显示预订按钮,用户未登录已不显示预订按钮
    booking = 1
    if 'user_id' in session:
        if house.user_id == session['user_id']:
            booking = 0
    else:
        booking = 0

    return jsonify(house=house.to_full_dict(), facility_list=facility_list, booking=booking)

@house_blueprint.route('/house/')
@is_login
def my_house():
    #我的房屋信息
    user = g.user
    user_id = user.id

    try:
        house1=House.query.filter(House.user_id == user_id).all()
    except Exception as e:
        logging.error(e)
        return  jsonify(code=RET.DATAERR,msg='查询失败')

    hlist=[i.to_dict() for i in house1]

    return jsonify(code=RET.OK,msg="OK" , hlist=hlist)

def area_get():
    area_list = redis_store.get('area_list')

    if not area_list:
        try:
            areas = Area.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(code=RET.DATAERR, msg=ret_map[RET.DATAERR])

        area_list = [area.to_dict() for area in areas]

        redis_store.set('area_list', json.dumps(area_list))
    else:
        area_list = json.loads(area_list)
    return area_list

def facility_get():
    facility_list = redis_store.get('facility_list')

    if not facility_list:
        try:
            facilitys = Facility.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(code=RET.DATAERR, msg=ret_map[RET.DATAERR])

        facility_list = [facility.to_dict() for facility in facilitys]

        redis_store.set('facility_list', json.dumps(facility_list))
    else:
        facility_list = json.loads(facility_list)
    return facility_list

@house_blueprint.route('/house/area_facility')
def area_facility():
    #查询地区
    areas_list = area_get()

    #查询房屋配置
    facilitys_list = facility_get()


    return jsonify(area=areas_list,facility=facilitys_list)

@house_blueprint.route('/house/image' ,methods=['POST'])
def house_image():
    #房屋的图片
    #获取参数
    house_id = request.form.get('house_id')
    file_image = request.files.get('house_image')
    #校验参数
    if not all([house_id,file_image]):
        return jsonify(code=RET.PARAMERR,msg='参数不全')

    if not re.match('image/.*', file_image.mimetype):
        return jsonify(code=RET.PARAMERR, msg='文件类型错误')
    #将图片保存到七牛云
    image_url = put_qiniu(file_image)
    #创建图片对象
    image = HouseImage()
    #数据入库
    image.house_id = house_id
    image.url = image_url


    try:
        image.add_update()
    except Exception as e:
        logging.error(e)
        return jsonify(code=RET.DBERR, msg='更新失败')

    try:
        house = House.query.get(house_id)
    except Exception as e:
        logging.error(e)
        return jsonify(code=RET.DATAERR,msg='查询失败')
    #判断房屋图片的数据
    if not house.index_image_url:
        house.index_image_url = image_url
        house.add_update()

    hlist = House.query.order_by(House.id.desc())[:5]
    hlist2 = [house.to_dict() for house in hlist]
    redis_store.setex('hlist', 24 * 3600, json.dumps(hlist2))

    return jsonify(code=RET.OK, url=current_app.config.get('QINIU_URL') + image_url)

@house_blueprint.route('/house/search')
def search():
    #获取搜索的参数

    aid = request.args.get('aid')
    sd = request.args.get('sd')
    ed  = request.args.get('ed')
    sk = request.args.get('sk')
    area = request.args.get('area')

    #检验参数
    if not aid:
        return jsonify(code=RET.PARAMERR,msg='地区不存在')

    hlist = House.query.filter(House.area_id == aid)

    if 'user_id' in session:
        hlist = hlist.filter(House.user_id != (session['user_id']))


    # 满足时间条件，当订单完成后再完成时间限制
    order_list = Order.query.filter(Order.status != 'REJECTED')
    # 情况一：
    # order_list1=Order.query.filter(Order.begin_date>=begin_date,Order.end_date<=end_date)
    # 情况二：
    order_list2 = order_list.filter(Order.begin_date < sd, Order.end_date > ed)
    # 情况三：
    order_list3 = order_list.filter(Order.end_date >= sd, Order.end_date <= ed)
    # 情况四：
    order_list4 = order_list.filter(Order.begin_date >= sd, Order.begin_date <= ed)
    # 获取订单中的房屋编号
    house_ids = [order.house_id for order in order_list2]  # [1,2,3]
    for order in order_list3:
        house_ids.append(order.house_id)
    for order in order_list4:
        if order.house_id not in house_ids:
            house_ids.append(order.house_id)
    hlist = hlist.filter(House.id.notin_(house_ids))
    #排序规则,默认根据最新排列
    sort = House.id.desc()
    if sk == 'booking':
        sort = House.order_count.desc()
    elif sk == 'price-inc':
        sort = House.price.asc()
    elif sk == 'price-des':
        sort = House.price.desc()
    hlist = hlist.order_by(sort)
    hlist2 = [house.to_dict() for house in hlist]

    # 获取地区信息
    if request.args.get('area', '0') == '1':
        alist = area_get()
    else:
        alist = []

    return jsonify(hlist=hlist2, alist=alist)



